/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 *
 * 我的工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './RetrieveRoomsViewScreen.Style'
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {retrieveRoomViewAs} from "./Actions";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import AntDesign from "react-native-vector-icons/AntDesign";
import {COLOR_FOCUS} from "../../../constant/PHColors";
import Entypo from "react-native-vector-icons/Entypo";
import HS_TouchableHighlight from "../../../hsstyle/HS_TouchableHighlight";

class RetrieveRoomsViewScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `选择房间`,
        headerRight: (
            <View/>
        )
    });

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {
            room_all:[],
            multi:this.props.navigation.getParam("multi")?this.props.navigation.getParam("multi"):false,
            checkedRoom:this.props.navigation.getParam("checkedRoom")?this.props.navigation.getParam("checkedRoom"):'',
            checkedRoomNew:[],          //选中房间信息 [{},{},{},{},{}]
            floor_open:{},          //展开的楼层     {"A_4":"open","A_5":"close"}
            floor_json:{},      //楼层对照名称        {"4":"4-4层","5":"5-5层"}
            floor_checked:[],      //选中房间信息


            building_open:{},          //展开的楼型      {"A":"open","B":"close"}
            build_json:{},      //楼型对照名称    {"A":"乡音酒店","B":"相恋酒店"}
            build_checked:[],      //选中房间信息

        };

        this.floor_c = [];
        this.building_c = [];
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onRetrieveRoomViewAs !== this.props.onRetrieveRoomViewAs && nextProps.onRetrieveRoomViewAs.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveRoomViewAs.RETURN === ReturnStatus.Success) {
                let RoomsViewArr = nextProps.onRetrieveRoomViewAs.DATA;

                let floor_checked = [];
                let build_checked = [];

                let floor_json = {};
                this.props.onCache.floor.map((item,index)=>{
                    floor_json[item.code]=item.descript1;
                    floor_checked.push(item.code);
                });

                let build_json = {};
                let building_open = {};
                this.props.onCache.building.map((item,index)=>{
                    build_json[item.code]=item.descript1;
                    building_open[item.code]="open";
                    build_checked.push(item.code);
                });

                let new_RoomsViewArr = [];
                let checkedRoomNew = [];
                RoomsViewArr.map((item,index)=>{
                    if(this.state.checkedRoom.split(',').indexOf(item.room)<0){
                        if(floor_checked.indexOf(item.floor)>=0){
                            floor_checked.splice(floor_checked.indexOf(item.floor),1);
                        }

                        if(build_checked.indexOf(item.building)>=0){
                            build_checked.splice(build_checked.indexOf(item.building),1);
                        }
                    }else{
                        checkedRoomNew.push(item)
                    }

                    if(build_json[item.building] && floor_json[item.floor]){
                        new_RoomsViewArr.push(item)
                    }


                });


                this.setState({
                    checkedRoomNew:checkedRoomNew,
                    room_all:new_RoomsViewArr,
                    building_open:building_open,
                    floor_json:floor_json,
                    build_json:build_json,
                    floor_checked:floor_checked,
                    build_checked:build_checked,
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onRetrieveRoomViewAs.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"wherestatus":{"All":"1"},"arg":{"arg":"房务"},"where":{"building":"","rmtype":"","floor":"","allSearch":"","source":"","market":"","features":"","grno":""}}
        dispatch(retrieveRoomViewAs(JSON.stringify(str),this.state.procedure))
    }

    render() {
        return (
            <SafeAreaView style={styles.body}>
                <View style={[styles.body, {paddingBottom: 50}]}>
                    <ScrollView style={styles.scrollView}>
                        {
                            (this.state.room_all.length>0)
                            &&
                            (
                                this.state.room_all.map((item,index)=>{
                                    return(
                                        this.room_render(item,index)
                                    )
                                })
                            )
                        }
                    </ScrollView>
                </View>

                <View style={styles.bodyBottom}>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.next_step()}>
                        <View style={styles.bodyBottomRight}>
                            <Text style={styles.cellTitleText}>
                                已选{this.state.checkedRoomNew.length}间，确认
                            </Text>
                        </View>
                    </TouchableOpacity>

                </View>
            </SafeAreaView>
        )
    };

    room_render(item,index){
        let html = [];

        if(this.building_c.indexOf(item.building)<0){
            let html1 = (
                <TouchableOpacity activeOpacity={0.9} key={"building_"+index} onPress={() => {
                    const json = this.state.building_open;
                    if(json[item.building]&&json[item.building]==="open"){
                        json[item.building]="close"
                    }else{
                        json[item.building]="open"
                    }
                    this.setState({
                        building_open: json
                    });
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox}>
                            {
                                (this.state.build_checked.indexOf(item.building)>=0 && this.state.multi===true )
                                    ?
                                    (<AntDesign name={'checkcircle'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}} onPress={()=>{
                                        let checkedRoom = this.state.checkedRoom;
                                        let checkedRoom_array = checkedRoom.split(',');
                                        this.state.room_all.map((value,key)=>{
                                            if(value.building===item.building){
                                                checkedRoom =  checkedRoom_array.splice(checkedRoom_array.indexOf(value.room),1);
                                            }
                                        })
                                        this.screenFresh(checkedRoom_array.join(','));
                                    }} />)
                                    :
                                    (<Entypo name={'circle'} size={23} style={{color: '#b3b9ba', marginLeft: 10}} onPress={()=>{
                                        let checkedRoom = this.state.checkedRoom;
                                        let checkedRoom_array = checkedRoom.split(',');
                                        this.state.room_all.map((value,key)=>{
                                            if(value.building===item.building && checkedRoom_array.indexOf(value.room)<0){
                                                checkedRoom_array.push(value.room)
                                            }
                                        })
                                        this.screenFresh(checkedRoom_array.join(','));
                                    }} />)
                            }
                            <Text style={styles.leftText}>
                                {this.state.build_json[item.building]}
                            </Text>
                        </View>
                        <View style={styles.rightBox}>
                            {
                                (this.state.building_open[item.building]==="open")
                                    ?
                                    (<Entypo name={'chevron-down'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}}/>)
                                    :
                                    (<Entypo name={'chevron-right'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}}/>)
                            }
                        </View>
                    </View>

                </TouchableOpacity>
            );
            html.push(html1);
            this.building_c.push(item.building);
        }

        if(this.floor_c.indexOf(item.building+'_'+item.floor)<0 && this.state.floor_json[item.floor] && this.state.building_open[item.building]==="open"){
            let html2 = (
                <TouchableOpacity activeOpacity={0.9} key={"floor_"+index} onPress={() => {
                    const json = this.state.floor_open;
                    if(json[item.building+"_"+item.floor]&&json[item.building+"_"+item.floor]==="open"){
                        json[item.building+"_"+item.floor]="close"
                    }else{
                        json[item.building+"_"+item.floor]="open"
                    }
                    this.setState({
                        floor_open: json
                    });
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox1}>
                            {
                                (this.state.floor_checked.indexOf(item.floor)>=0 && this.state.multi===true)
                                    ?
                                    (<AntDesign name={'checkcircle'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}} onPress={()=>{
                                        let checkedRoom = this.state.checkedRoom;
                                        let checkedRoom_array = checkedRoom.split(',');
                                        this.state.room_all.map((value,key)=>{
                                            if(value.floor===item.floor){
                                                checkedRoom =  checkedRoom_array.splice(checkedRoom_array.indexOf(value.room),1);
                                            }
                                        })
                                        this.screenFresh(checkedRoom_array.join(','));
                                    }} />)
                                    :
                                    (<Entypo name={'circle'} size={23} style={{color: '#b3b9ba', marginLeft: 10}} onPress={()=>{
                                        let checkedRoom = this.state.checkedRoom;
                                        let checkedRoom_array = checkedRoom.split(',');

                                        this.state.room_all.map((value,key)=>{
                                            if(value.floor===item.floor && checkedRoom_array.indexOf(value.room)<0){
                                                checkedRoom_array.push(value.room)
                                            }
                                        })

                                        this.screenFresh(checkedRoom_array.join(','));
                                    }} />)
                            }
                            <Text style={styles.leftText}>
                                {this.state.floor_json[item.floor]}
                            </Text>
                        </View>
                        <View style={styles.rightBox}>
                            {
                                (this.state.floor_open[item.building+'_'+item.floor]==="open")
                                    ?
                                    (<Entypo name={'chevron-down'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}}/>)
                                    :
                                    (<Entypo name={'chevron-right'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}}/>)
                            }
                        </View>
                    </View>

                </TouchableOpacity>
            );
            html.push(html2);
            this.floor_c.push(item.building+'_'+item.floor);
        }

        if(this.state.floor_open[item.building+'_'+item.floor]==="open"){
            let html3 = (
                <TouchableOpacity activeOpacity={0.9} key={"room_"+index} onPress={() => {
                    let checkedRoom = this.state.checkedRoom;
                    let checkedRoom_array = [];
                    if(this.state.multi){
                        checkedRoom_array = checkedRoom.split(',');
                        if(checkedRoom_array.indexOf(item.room)>=0 ){
                            checkedRoom_array.splice(checkedRoom_array.indexOf(item.room),1)
                            checkedRoom =  checkedRoom_array.join(',');
                        }else{
                            checkedRoom_array.push(item.room);
                            checkedRoom = checkedRoom_array.join(',');
                        }
                    }else{
                        checkedRoom = item.room;
                    }

                    this.screenFresh(checkedRoom);
                }}>
                    <View style={styles.boxBody}>
                        <View style={styles.leftBox2}>
                            {
                                (this.state.checkedRoom.split(',').indexOf(item.room)>=0 )
                                    ?
                                    (<AntDesign name={'checkcircle'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}} />)
                                    :
                                    (<Entypo name={'circle'} size={23} style={{color: '#b3b9ba', marginLeft: 10}} />)
                            }
                            <Text style={styles.leftText}>
                                {item.room}
                            </Text>
                        </View>
                        <View style={styles.rightBox}>
                            {/*<Text style={styles.leftText}>*/}
                                {/*{item.qty}*/}
                            {/*</Text>*/}
                        </View>
                    </View>

                </TouchableOpacity>
            );
            html.push(html3);
        }

        if(index+1===this.state.room_all.length){
            this.building_c = [];
            this.floor_c = [];
        }

        return html
    };

    screenFresh=(checkedRoom)=>{
        if(checkedRoom.indexOf(',') === 0){
            checkedRoom = checkedRoom.replace(',','');
        }
        let RoomsViewArr = this.state.room_all;

        let floor_checked = [];
        let build_checked = [];

        this.props.onCache.floor.map((item,index)=>{
            floor_checked.push(item.code);
        });

        this.props.onCache.building.map((item,index)=>{
            build_checked.push(item.code);
        });

        let checkedRoomNew = [];
        RoomsViewArr.map((item,index)=>{
            if(checkedRoom.split(',').indexOf(item.room)<0){
                if(floor_checked.indexOf(item.floor)>=0){
                    floor_checked.splice(floor_checked.indexOf(item.floor),1);
                }

                if(build_checked.indexOf(item.building)>=0){
                    build_checked.splice(build_checked.indexOf(item.building),1);
                }
            }else{
                checkedRoomNew.push(item)
            }
        });
        this.setState({
            checkedRoomNew:checkedRoomNew,
            checkedRoom:checkedRoom,
            floor_checked:floor_checked,
            build_checked:build_checked,
        })
    };

    next_step=()=>{
        this.props.navigation.state.params.callBack(this.state.checkedRoomNew);
    }
}

const props = state => {
    return {
        onRetrieveRoomViewAs:state.onRetrieveRoomViewAs,
        onCache: state.onCache,
    }
}

export default RetrieveRoomsViewScreen = connect(props)(RetrieveRoomsViewScreen);